package cn.legend.travel.admin.authorize.service.abs;

import cn.legend.travel.admin.authorize.pojo.param.UserLoginParam;
import cn.legend.travel.admin.authorize.pojo.vo.UserLoginInfoVO;
import cn.legend.travel.admin.authorize.pojo.vo.UserLoginResultVO;
import cn.legend.travel.admin.authorize.service.IUserService;
import cn.legend.travel.common.enumerator.ServiceCode;
import cn.legend.travel.common.exception.ServiceException;
import cn.legend.travel.common.pojo.po.UserStatePO;
import cn.legend.travel.common.util.JwtUtils;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequiredArgsConstructor
public abstract class AbstractUserService implements IUserService {
    @Value("${travel.jwt.secret-key}")
    private String secretKey;

    protected void checkLogin(UserLoginInfoVO loginInfo, UserLoginParam param, PasswordEncoder encoder) {
        if (loginInfo == null) {
            throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED, "登陆失败,用户名或密码错误");
        }
        if (loginInfo.getState() == 0) {
            throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED_DISABLED, "登陆失败,账号已被禁用");
        }
        if (!encoder.matches(param.getPassword(), loginInfo.getPassword())) {
            throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED, "登陆失败,用户名或密码错误");
        }
    }

    protected UserLoginResultVO getLoginResult(UserLoginInfoVO loginInfo) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", loginInfo.getId());
        claims.put("username", loginInfo.getUsername());
        String jwt = JwtUtils.generate(claims, secretKey);
        UserLoginResultVO loginResult = new UserLoginResultVO();
        loginResult.setId(loginInfo.getId());
        loginResult.setUsername(loginInfo.getUsername());
        loginResult.setToken(jwt);
        loginResult.setAuthorities(loginInfo.getPermissions());
        return loginResult;
    }

    protected UserStatePO getUserState(UserLoginInfoVO loginInfo) {
        UserStatePO userState = new UserStatePO();
        userState.setState(loginInfo.getState());
        List<GrantedAuthority> authorities = new ArrayList<>();
        loginInfo.getPermissions().forEach(permission -> authorities.add(new SimpleGrantedAuthority(permission)));
        String jsonString = JSON.toJSONString(authorities);
        userState.setAuthoritiesJsonString(jsonString);
        return userState;
    }
}
